package cn.edu.cqu.bysj.services.hibernate;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.edu.cqu.bysj.domains.TicketPrice;
import cn.edu.cqu.bysj.services.TicketPriceCRUD;

@Service("TicketPriceCRUDHibernate")
public class TicketPriceCRUDHibernate implements TicketPriceCRUD
{
	private HibernateTemplate ht;
	@Autowired
	public void setSessionFactory(SessionFactory sessionFactory) {
		ht = new HibernateTemplate(sessionFactory);
	}
	
	@Transactional
	@Override
	public void add(TicketPrice ticketPrice)
	{
		ht.save(ticketPrice);
	}
	
	@Override
	public TicketPrice getByNo(int ticketPriceNo)
	{
		return ht.get(TicketPrice.class, ticketPriceNo);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<TicketPrice> getByTrainNo(String trainNo)
	{
		String sql = "from TicketPrice t where t.trainNo=?";
		List<TicketPrice> tps = (List<TicketPrice>) ht.find(sql, new Object[]{trainNo});
		if (tps.size() == 0)
			return null;
		return tps;
	}

	@SuppressWarnings("unchecked")
	@Override
	public TicketPrice getByTrainStationNo(String trainNo, String StationNo)
	{
		String sql = "from TicketPrice t where t.trainNo=? and t.stationNo=?";
		List<TicketPrice> tps = (List<TicketPrice>) ht.find(sql, new Object[]{trainNo,StationNo});
		if (tps.size() == 0)
			return null;
		return tps.get(0);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<TicketPrice> getAll()
	{
		List<TicketPrice> tps = (List<TicketPrice>) ht.find("from TicketPrice");
		return tps;
	}

	@Transactional
	@Override
	public void edit(int ticketPriceNo, TicketPrice ticketPrice)
	{
		TicketPrice tp = this.getByNo(ticketPriceNo);
		tp.setA1(ticketPrice.getA1());
		tp.setA3(ticketPrice.getA3());
		tp.setA4(ticketPrice.getA4());
		tp.setA9(ticketPrice.getA9());
		tp.setA6(ticketPrice.getA6());
		tp.setMIN(ticketPrice.getMIN());
		tp.setP(ticketPrice.getP());
		tp.setM(ticketPrice.getM());
		tp.setO(ticketPrice.getO());
		tp.setOT(ticketPrice.getOT());
		tp.setStationNo(ticketPrice.getStationNo());
		tp.setTrainNo(ticketPrice.getTrainNo());
		tp.setWZ(ticketPrice.getWZ());
		ht.update(tp);
	}

	@Transactional
	@Override
	public void deleteByTrainNo(String trainNo)
	{
		List<TicketPrice> tps = this.getByTrainNo(trainNo);
		for (TicketPrice ticketPrice : tps)
		{
			ht.delete(ticketPrice);
		}
	}

	@Transactional
	@Override
	public void deleteByNo(int ticketPriceNo)
	{
		TicketPrice tp = this.getByNo(ticketPriceNo);
		ht.delete(tp);
	}

	@Transactional
	@Override
	public void deleteAll()
	{
		List<TicketPrice> tps = this.getAll();
		for (TicketPrice ticketPrice : tps)
		{
			ht.delete(ticketPrice);
		}

	}
}
